
package com.eva.android.widget;

import android.content.Context;
import android.os.Handler;

public abstract class StopableWraper
{
	private Context context = null;
    
	private Handler handler = null;
	private Runnable runnable = null;
    
	/** 正在执行中 */
    private boolean running = false;
    
    /** 延迟时间 */
    protected long delayMillis = 0;
    
    public StopableWraper(Context context, long delayMillis)
    {
    	this.context = context;
    	this.delayMillis = delayMillis;
    	
    	init();
    }
    
    protected void init()
    {
    	handler = new Handler();
		runnable = new Runnable(){
			@Override
			public void run()
			{
				stopImpl();
				running = false;
			}
		};
    }
	
    // 每次调用start的时候就是保证动画不被停止，否则将在一段延迟后停
    // 止动画（用于没办法预知应用层停止动作的场景下能自动停止）
	public void start()
	{
		if(!running)
		{
			running = true;
			startImpl();
		}
		
		// 先remove
		handler.removeCallbacks(runnable);
		// 无条件
		handler.postDelayed(runnable, delayMillis);
	}
	
	// 强制退出事件循环
	public void enforceStop(boolean needInvodeStopImpl)
	{
		handler.removeCallbacks(runnable);
		running = false;
		if(needInvodeStopImpl)
			stopImpl();
	}
	
	protected abstract void stopImpl();
	
	protected abstract void startImpl();
}
